import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Link } from 'react-router';
import { Button, Row, Form, Input, message } from 'antd';
import NavBar from '../common/NavBar';
import ContentBody from '../common/ContentBody';
import api from '../api';

import styles from './WeixinButtons.scss';

export default class WeiXinSetting extends React.Component {
    constructor(props, context){
        super(props, context);
        this.state={
            button:[

            ],
            buttonIndex:0,
            sub_buttonIndex:0,
            loadingFlag:true
        };
    }
    async componentWillMount(){
        var result = await api('/operation/weixin/getbutton');

        let res = JSON.parse(result.data);


        if(res.errcode){
            result.data = null;
        }

        let button = JSON.parse(result.data||'{"menu":{"button":[]}}').menu.button;
        if(button.length>0){
            button[0].active = true;
            let sub_button = button[0].sub_button;
            if(sub_button&&sub_button.length>0){
                sub_button[0].active = true
            }
        }
        this.setState({
            button,
            loadingFlag:false
        })


    }
    componentDidMount(){

    }

    componentWillReceiveProps(nextProps){

    }

    //
    handleAddButton(){
        let {button} = this.state;
        this.clearActive(button);
        button.push({
            name:'菜单名称',
            type:'view',
            sub_button:[],
            url:'',
            active:true
        });
        this.setState({
            button,
            buttonIndex:button.length-1
        });
    }

    //添加子按钮
    handleAddSubButton(index,e){
        e.stopPropagation();
        let {button} = this.state;
        this.clearActive(button,index);
        button[index].type='click';
        button[index].url = '';
        button[index].sub_button.unshift({
            name:'子菜单名称',
            type:'view',
            sub_button:[],
            url:'',
            active:true
        });
        // console.log(button)
        this.setState({
            button,
            buttonIndex:index,
            sub_buttonIndex:0
        });
    }

    clearActive(button,index){
        button.forEach((item,i)=>{
            if(index!=i){
                item.active = false;
            }
            if(item.sub_button.length>0){
                this.clearActive(item.sub_button)
            }

        })
        // return button
    }

    handleSelected(parentIndex,index,e){
         e.stopPropagation();
        let {button} = this.state;
        this.clearActive(button,parentIndex);

        button[parentIndex].active = true;
        if(index!=undefined){
            let sub_button = button[parentIndex].sub_button[index].active = true;
        }


        this.setState({
            button,
            buttonIndex:parentIndex,
            sub_buttonIndex:index
        })
    }

    handleMenuChange(filed,length,e){
        let {button,buttonIndex,sub_buttonIndex} = this.state;

        let value = e.target.value;
        value = length?this.checkLength(value,length):value
        if(/^sub_/g.test(filed)){
            button[buttonIndex].sub_button[sub_buttonIndex][filed.replace(/sub_/g,'')] = value;
        }else{
            button[buttonIndex][filed] = value;
        }


        this.setState({button});
    }

    //
    checkLength(value,length){
        length = length * 2;
        var n = 0,text = '';
        for(var i=0 ; i < value.length ; i ++){
            if(value.charCodeAt(i) < 128 ){
                n++;
            }else{
                n += 2
            }
            if(n <= length){
                text += value[i]
            }
        }
        return text;
    }

    deleteMenu(filed){
        let {button,buttonIndex,sub_buttonIndex} = this.state;
        if(filed=='button'){
            button.splice(buttonIndex,1);
            this.setState({button,buttonIndex:buttonIndex-1,sub_buttonIndex:null})
        }
        if(filed=='sub_button'){
            button[buttonIndex].sub_button.splice(sub_buttonIndex,1);
            let sub_button = button[buttonIndex].sub_button;
            if(sub_button.length>0){
                sub_button[0].active = true;
            }else{
                button[buttonIndex].type = 'view';
            }

            this.setState({
                button,
                buttonIndex,
                sub_buttonIndex:0
            })
        }

    }

    async save(){

        var {button} = this.state;

        this.saveError = [] ;
        this.checkFiled(button);

        if(this.saveError.length>0){
            // Snack.snack(this,this.saveError[0]);
            message.error(this,this.saveError[0], 5);
            return;
        }
        this.setState({loadingFlag:true});

        var result = await api('/operation/weixin/setbutton',{button});

        this.setState({loadingFlag:false});

        if(result.cd!=0){
            // Snack.snack(this,result.msg);
            message.error(this,result.msg, 5);
            return;
        }
        // Snack.snack(this,'保存成功');
        message.success("保存成功", 5);
    }

    checkFiled(button){
        for(var i=0 ;i < button.length ; i++){
            var item = button[i];
            item.sub_button = item.sub_button ||[]
            if (!item.name){
                this.saveError.push('菜单名称不能为空')
            }else if(item.type == 'view' && !item.url){
                this.saveError.push(item.name+'跳转地址不能为空')
            }else if(item.sub_button.length>0) {
                this.checkFiled(item.sub_button)
            }
        }
    }


    renderConfigHtml(){
        let {button,buttonIndex,sub_buttonIndex} = this.state;
        if(button.length==0) return;

        let buttonConfig = button[buttonIndex];

        if(buttonConfig.sub_button.length>0&&sub_buttonIndex!=null){
            let sub_buttonConfig = buttonConfig.sub_button[sub_buttonIndex]||{};
            return (
                <div className={styles.configview}>
                    <div className={styles.configtitle}>
                        <span>子菜单名称</span>
                        <a
                            href="javascript:void 0;"
                            onClick={this.deleteMenu.bind(this,'sub_button')}
                        >删除子菜单</a>
                    </div>
                    <div className={styles.configcontent}>
                        <div className='col-md-12' style={{marginTop:'20px'}}>
                            <label>子菜单名称</label>
                            <input
                                type="text"
                                className="form-control"
                                value={sub_buttonConfig.name}
                                placeholder="请输入子菜单名称"
                                onChange={this.handleMenuChange.bind(this,'sub_name',8)}
                            />
                        </div>
                        <div className='col-md-12' style={{color:'#999',fontSize:'12px'}} >
                        字数不超过8个汉字或16个字母
                        </div>
                        <div className='col-md-12' style={{marginTop:'20px'}}>
                            <label>跳转地址</label>
                            <input
                                type="text"
                                className="form-control"
                                placeholder="请输入跳转地址"
                                value={sub_buttonConfig.url}
                                onChange={this.handleMenuChange.bind(this,'sub_url',null)}
                            />
                        </div>
                    </div>
               </div>
            )
        }

        return (
            <div className={styles.configview}>
                <div className={styles.configtitle}>
                    <span>菜单名称</span>
                    <a
                        href="javascript:void 0;"
                        onClick={this.deleteMenu.bind(this,'button')}
                    >删除菜单</a>
                </div>
                <div className={styles.configcontent}>
                    <div className='col-md-12' style={{marginTop:'20px'}}>
                        <label>菜单名称</label>
                        <input
                            type="text"
                            className="form-control"
                            placeholder="菜单名称"
                            value={buttonConfig.name}
                            onChange={this.handleMenuChange.bind(this,'name',4)}
                        />
                    </div>
                    <div className='col-md-12' style={{color:'#999',fontSize:'12px'}} >
                    字数不超过4个汉字或8个字母
                    </div>
                    {buttonConfig.sub_button.length>0?null:
                        <div className='col-md-12' style={{marginTop:'20px'}}>
                            <label>跳转地址</label>
                            <input
                                type="text"
                                className="form-control"
                                value={buttonConfig.url}
                                placeholder="请输入跳转地址"
                                onChange={this.handleMenuChange.bind(this,'url',null)}
                            />
                        </div>

                    }

                </div>
           </div>
        )

    }

    addClass(ary){
        return ary.join(' ');
    }

    render() {
        let {button,loadingFlag} = this.state;
        return (
             <div >
                <NavBar navs={[{title:'微信管理'}]} />
                <ContentBody className='container'>
                    <div className="content">
                        <div className="box">
                            <div className="box-header">
                              <h3 className="box-title">编辑</h3>
                            </div>
                            <div className="box-body">
                               <div className={styles.wrapper}>
                                   <div className={styles.weixinView}>

                                       <ul className={styles.weixinButtons}>
                                           {button.map((item,index)=>{
                                                return (
                                                    <li
                                                        key={index}
                                                        className={item.active?this.addClass([styles.button,styles.focus]):styles.button}
                                                        onClick={this.handleSelected.bind(this,index,null)}
                                                    >
                                                        <span>{item.name}</span>
                                                        <div className={styles.subButtons}>
                                                            <ul >
                                                                {item.sub_button.map((item2,index2)=>{
                                                                    return (
                                                                         <li
                                                                            key={index2}
                                                                            className={item2.active?styles.focus:''}
                                                                            onClick={this.handleSelected.bind(this,index,index2)}
                                                                        >
                                                                            {item2.name}
                                                                        </li>
                                                                    )

                                                                })}
                                                            </ul>
                                                            <a className={styles.addButton} onClick={this.handleAddSubButton.bind(this,index)}>
                                                                <i className='fa fa-plus'></i>
                                                            </a>
                                                        </div>

                                                    </li>
                                                )
                                           })}
                                           {button.length==0?
                                            <li className={this.addClass([styles.button,styles.focus])} onClick={this.handleAddButton.bind(this)}><i className='fa fa-plus'></i></li>
                                            :button.length>0&&button.length<3?
                                            <li className={styles.button} onClick={this.handleAddButton.bind(this)}><i className='fa fa-plus'></i></li>
                                            :null
                                           }

                                       </ul>
                                   </div>
                                   {this.renderConfigHtml()}
                               </div>
                               {button.length>0?
                                    <div className="row" style={{margin:'20px 0'}}>
                                        <div className="col-md-12" style={{textAlign:"center"}}>
                                            <div className="btn-group" role="group"  >
                                                <button
                                                    type="button"
                                                    onClick={this.save.bind(this)}
                                                    className="btn btn-primary"
                                                    style={{marginLeft:"20px"}}
                                                >
                                                保存
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                    :null
                               }

                            </div>
                        {loadingFlag?
                            <div className="overlay">
                              <i className="fa fa-refresh fa-spin"></i>
                            </div>
                            :""
                        }
                        </div>
                    </div>
                </ContentBody>
            </div>
        );
    }
}
WeiXinSetting.contextTypes= { router: React.PropTypes.object.isRequired};
